/*
    File : core_portme.c
*/
/*
    Author : Shay Gal-On, EEMBC
    Legal : TODO!
*/

#include "sym32l010_hal_sysctrl.h"
#include "sym32l010_hal_systick.h"
#include "sym32l010_hal_gpio.h"
#include "sym32l010_startkit_board.h"
#include "coremark.h"

static void UserError(void);

//----------------------------------------------------------------
// 定义时钟频率参数
#define SYSCLK_HSI4M            4000000UL
#define SYSCLK_HSI8M            8000000UL
#define SYSCLK_HSI12M          12000000UL
#define SYSCLK_HSI24M          24000000UL
#define SYSCLK_HSI48M          48000000UL

//----------------------------------------------------------------
// 配置CoreMark使用的时钟 (用户配置)
#define USER_SYSCLK_CLK        SYSCLK_HSI48M

//----------------------------------------------------------------
// 根据不同的时钟配置迭代次数，按要求保证CoreMark运行时间超过10S
#if (USER_SYSCLK_CLK == SYSCLK_HSI4M)
  #define ITERATIONS         200                                      // SysClk = HCLK = PCLK = SYSCLK_HSI4M
#elif (USER_SYSCLK_CLK == SYSCLK_HSI8M)
  #define ITERATIONS         340                                      // SysClk = HCLK = PCLK = SYSCLK_HSI8M
#elif (USER_SYSCLK_CLK == SYSCLK_HSI12M)
  #define ITERATIONS         420                                      // SysClk = HCLK = PCLK = SYSCLK_HSI12M
#elif (USER_SYSCLK_CLK == SYSCLK_HSI24M)
  #define ITERATIONS         1000                                     // SysClk = HCLK = PCLK = SYSCLK_HSI24M
#elif (USER_SYSCLK_CLK == SYSCLK_HSI48M)
  #define ITERATIONS          800                                     // SysClk = HCLK = PCLK = SYSCLK_HSI48M
#endif

//----------------------------------------------------------------
// 配置每秒的uwTick数，使用SysTick计时 每秒1000次
#define EE_TICKS_PER_SEC       1000UL

//----------------------------------------------------------------
// CoreMark相关变量定义
#if VALIDATION_RUN
    volatile ee_s32 seed1_volatile=0x3415;
    volatile ee_s32 seed2_volatile=0x3415;
    volatile ee_s32 seed3_volatile=0x66;
#endif
#if PERFORMANCE_RUN
    volatile ee_s32 seed1_volatile=0x0;
    volatile ee_s32 seed2_volatile=0x0;
    volatile ee_s32 seed3_volatile=0x66;
#endif
#if PROFILE_RUN
    volatile ee_s32 seed1_volatile=0x8;
    volatile ee_s32 seed2_volatile=0x8;
    volatile ee_s32 seed3_volatile=0x8;
#endif
    volatile ee_s32 seed4_volatile=ITERATIONS;
    volatile ee_s32 seed5_volatile=0;

/* Porting : Timing functions
    How to capture time and convert to seconds must be ported to whatever is supported by the platform.
    e.g. Read value from on board RTC, read value from cpu clock cycles performance counter etc.
    Sample implementation for standard time.h and windows.h definitions included.
*/
/* Define : TIMER_RES_DIVIDER
    Divider to trade off timer resolution and total time that can be measured.

    Use lower values to increase resolution, but make sure that overflow does not occur.
    If there are issues with the return value overflowing, increase this value.
    */
//#define NSECS_PER_SEC CLOCKS_PER_SEC
//#define CORETIMETYPE clock_t
//#define GETMYTIME(_t) (*_t=clock())
//#define MYTIMEDIFF(fin,ini) ((fin)-(ini))
//#define TIMER_RES_DIVIDER 1
//#define SAMPLE_TIME_IMPLEMENTATION 1
//#define EE_TICKS_PER_SEC (NSECS_PER_SEC / TIMER_RES_DIVIDER)

// ** Define Host specific (POSIX), or target specific global time variables. */
//static CORETIMETYPE start_time_val, stop_time_val;


#define SysTick_Counter_Disable ((uint32_t)0xFFFFFFFE)
#define SysTick_Counter_Enable ((uint32_t)0x00000001)
#define SysTick_Counter_Clear ((uint32_t)0x00000000)

/* Function : start_time
    This function will be called right before starting the timed portion of the benchmark.

    Implementation may be capturing a system timer (as implemented in the example code)
    or zeroing some system parameters - e.g. setting the cpu clocks cycles to 0.
*/
void start_time(void) {
    uwTick = 0;
    SysTick_Config(SystemCoreClock/1000);
}
/* Function : stop_time
    This function will be called right after ending the timed portion of the benchmark.

    Implementation may be capturing a system timer (as implemented in the example code)
    or other system parameters - e.g. reading the current value of cpu cycles counter.
*/
void stop_time(void) {
    /* Stop the Timer and get the encodingtime */
    SysTick->CTRL &=SysTick_Counter_Disable;

    /* Clear the SysTick Counter */
    SysTick->VAL = SysTick_Counter_Clear;
}
/* Function : get_time
    Return an abstract "ticks" number that signifies time on the system.

    Actual value returned may be cpu cycles, milliseconds or any other value,
    as long as it can be converted to seconds by <time_in_secs>.
    This methodology is taken to accomodate any hardware or simulated platform.
    The sample implementation returns millisecs by default,
    and the resolution is controlled by <TIMER_RES_DIVIDER>
*/
CORE_TICKS get_time(void) {
    CORE_TICKS elapsed = (CORE_TICKS)uwTick;
    return elapsed;
}
/* Function : time_in_secs
    Convert the value returned by get_time to seconds.

    The <secs_ret> type is used to accomodate systems with no support for floating point.
    Default implementation implemented by the EE_TICKS_PER_SEC macro above.
*/
secs_ret time_in_secs(CORE_TICKS ticks) {
    secs_ret retval=((secs_ret)ticks) / (secs_ret)EE_TICKS_PER_SEC;
    return retval;
}

ee_u32 default_num_contexts=1;

/* Function : portable_init
    Target specific initialization code
    Test for some common mistakes.
*/
void portable_init(core_portable *p, int *argc, char *argv[])
{
    //------------------------------------------------------------
    // 初始化板载LED(PA03)
    Bsp_Led_Init();

    //------------------------------------------------------------
    // 配置系统时钟
    switch (USER_SYSCLK_CLK)
    {
        case SYSCLK_HSI4M:
            HAL_SysCtrl_HSI_SetDiv(HSIOSC_TO_HSI4MHZ);
            break;
        case SYSCLK_HSI8M:
            HAL_SysCtrl_HSI_SetDiv(HSIOSC_TO_HSI8MHZ);
            break;
        case SYSCLK_HSI12M:
            HAL_SysCtrl_HSI_SetDiv(HSIOSC_TO_HSI12MHZ);
            break;
        case SYSCLK_HSI24M:
            HAL_SysCtrl_HSI_SetDiv(HSIOSC_TO_HSI24MHZ);
            break;
        case SYSCLK_HSI48M:
            HAL_SysCtrl_ConfigWaitCycle(SYSCLK_HSI48M);
            HAL_SysCtrl_HSI_SetDiv(HSIOSC_TO_HSI48MHZ);
            break;
        default:
            UserError();
            break;
    }

    //------------------------------------------------------------
    // 更新内核时钟频率
    SystemCoreClock = USER_SYSCLK_CLK;

    //------------------------------------------------------------
    // 初始化板载UART
    Bsp_Uart_Init(SystemCoreClock, 115200);

    //------------------------------------------------------------
    // 开启SysTick内核中断，不使用中断
    NVIC_ClearPendingIRQ(SysTick_IRQn);
    NVIC_SetPriority(SysTick_IRQn, 1);
    NVIC_EnableIRQ(SysTick_IRQn);

    printf("\r\nCoremark test start......\r\n");

    if (sizeof(ee_ptr_int) != sizeof(ee_u8 *)) {
        ee_printf("ERROR! Please define ee_ptr_int to a type that holds a pointer!\n");
    }
    if (sizeof(ee_u32) != 4) {
        ee_printf("ERROR! Please define ee_u32 to a 32b unsigned type!\n");
    }
    p->portable_id=1;

    //------------------------------------------------------------
    // 设置UART_TXD管脚为ANALOG状态，以减小功耗
    BSP_UART_TXD_PORT->ANALOG |= BSP_UART_TXD_PIN;
}

/* Function : SysTick_Handler
   SysTick中断服务程序
*/
void SysTick_Handler(void)
{
    uwTick += 1;
}

/* Function : UserError
  不符合预期时执行的程序
*/
static void UserError(void)
{
    HAL_SysCtrl_HSI_Enable(HSIOSC_TO_HSI8MHZ);
    HAL_SysCtrl_SysClk_Switch(SYSCTRL_SYSCLKSRC_HSI);
    HAL_SysCtrl_ConfigWaitCycle(8000000);
    while (1)
    {
        BSP_LED_TOG();
        FirmwareDelay(80000);
    }
}

/* Function : portable_fini
    Target specific final code
*/
void portable_fini(core_portable *p)
{
    p->portable_id=0;
}

